<?php

define("MAX_RECORDS", 16);
define("RECORDS_FILE_NAME", "records.txt");

/*
* 
*
*/
function readTable() {

	// check file exist
	if (!file_exists(RECORDS_FILE_NAME)) throw new Exception("Error: can't open records file");
	
	$recordsFile = file(RECORDS_FILE_NAME);
	
	if ($recordsFile == FALSE) throw new Exception("Error: can't open records file");
	
	$recordsNum = count($recordsFile);
	
	if ($recordsNum > MAX_RECORDS) throw new Exception("Error: too many records in file");
	
	$recordsTable = array();
	
	// read each record and add it to the array
	if ($recordsNum > 0) {
		
		foreach($recordsFile as $line) {
			array_push($recordsTable, explode(",", trim($line)));
		}
	}

	return $recordsTable;
}

/*
*
*
*/
function getLastRecord($recordsTable) {
	return $recordsTable[count($recordsTable)-1][1];
}

/*
*
*
*/
function getTopRecord($recordsTable) {
	return $recordsTable[0][1];
}

/*
*
*
*/
function cmpRecords($recordA, $recordB)
{
    if ($recordA[1] == $recordB[1]) {
        return 0;
    }
    return ($recordA[1] > $recordB[1]) ? -1 : 1;
}

/*
*
*
*/
function checkInt($str)
{
	return  is_numeric($str) && intval($str) - $str == 0;
}

/*
*
*
*/
function writeRecord($name, $value, $recordsTable) {

	$newName = htmlspecialchars(stripslashes($name));
	$newName = str_replace(',', '.', $newName);
	$newName = substr($newName, 0, 20);
	
	if (empty($newName)) $newName = "Unknown Hero"; // :DDDDD

	if (!file_exists(RECORDS_FILE_NAME)) {
		if (!touch(RECORDS_FILE_NAME)) {
			throw new Exception("Error: can't touch records file");
		}
	}

	if (!checkInt($value) ||
		(count($recordsTable) >= MAX_RECORDS && $value < getLastRecord($recordsTable))) {
		throw new Exception("Error: fictive value");
	}
	
	$tmpTable = $recordsTable;
	
	array_push($tmpTable, array($name, $value));
	
	usort($tmpTable, "cmpRecords");

	$newRecordsTable = array_slice($tmpTable, 0, MAX_RECORDS);

	if ($fp = fopen(RECORDS_FILE_NAME, "w")) { 
		if (flock($fp, LOCK_EX)) { 
			foreach ($newRecordsTable as $record) {
				fwrite($fp, $record[0].",".$record[1]."\n");
			}
			flock($fp, LOCK_UN); 
		} 
		fclose($fp); 
	} else {
		throw new Exception("Error: can't open records file on write");
	}
}


try {
	header('Access-Control-Allow-Origin: *');

	$recordsTable = readTable();
	
	if (isset($_POST["add"])) {
		$name = $_POST["name"];
		$score = $_POST["score"];
		if (isset($name) && isset($score)) {
			writeRecord($name, $score, $recordsTable);
		}
		die("OK");
	}
	
	if (isset($_GET["get"])) {
		echo '<table id="recordsTable">';
		
		foreach ($recordsTable as $record) {
			echo '<tr><td>'.$record[0].'</td><td>'.$record[1].'</tr>';
		}
		
		echo '</table>';
		return;
	}

	if (isset($_GET["top"])) {
		echo getTopRecord($recordsTable);
		return;
	}

	if (isset($_GET["last"])) {
		echo getLastRecord($recordsTable);
		return;
	}

	if (isset($_GET["num"])) {
		echo count($recordsTable);
		return;
	}

	throw new Exception("Error: incorrect request");
	
} catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n";
}
?>